package com.prd.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.config.LoginInterceptor;
import com.prd.dto.EntReportInstructDto;
import com.prd.mapper.EntReportMapper;
import com.prd.model.EntReport;
import com.prd.model.LoginUser;
import com.prd.service.EntReportService;
import com.prd.service.UserService;
import com.prd.util.StringsUtils;
import com.prd.util.UserInfoUtil;
import com.prd.vo.EntReportVo;
import com.prd.vo.UserBaseVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntReportServiceImpl extends ServiceImpl<EntReportMapper, EntReport> implements EntReportService {

    @Autowired
    private EntReportMapper entReportMapper;

    @Autowired
    private UserService userService;

    @Override
    public List<EntReport> listInfo(String day, Integer type, Integer form) {
//        1:我发起、2：我接收、3：已批示、4：我编制
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        LambdaQueryWrapper<EntReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(type != null, EntReport::getType, type);
        lambdaQueryWrapper.apply(StringUtils.isNotBlank(day), "DATE(end_time) = {0}", day);
        //1:我发起
        if (form == 1) {
            lambdaQueryWrapper.eq(EntReport::getCreateId, loginUser.getId());
        } else if (form == 2) {//2：我接收
            lambdaQueryWrapper.eq(EntReport::getSuperior, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntReport::getReporter, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntReport::getJoint, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntReport::getMake, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntReport::getCompile, loginUser.getId());
        } else if (form == 3) {//3：已批示
            lambdaQueryWrapper.isNotNull(EntReport::getInstructType);
            lambdaQueryWrapper.eq(EntReport::getInstructPerson, loginUser.getId());
        } else if (form == 4) {//4：我编制
            lambdaQueryWrapper.eq(EntReport::getCompile, loginUser.getId());
        } else {
            throw new RuntimeException("找不到对应的编号！");
        }
        List<EntReport> reportList = entReportMapper.selectList(lambdaQueryWrapper);

        reportList.stream().forEach(item -> {
            List<Long> arrayList = new ArrayList<>();
            Long reporter = null;
            Long superior = null;
            if (StringUtils.isNotBlank(item.getReporter())) {
                reporter = Long.parseLong(item.getReporter());
                arrayList.add(reporter);
            }
            if (StringUtils.isNotBlank(item.getSuperior())) {
                superior = Long.parseLong(item.getSuperior());
                arrayList.add(superior);
            }
            arrayList.stream().distinct().collect(Collectors.toList());
            List<UserBaseVo> listUser = userService.listName(arrayList.toArray(new Long[arrayList.size()]));
            for (UserBaseVo userBaseVo : listUser) {
                if (reporter == userBaseVo.getId()) {
                    item.setReporter(userBaseVo.getMerge());
                }
                if (superior == userBaseVo.getId()) {
                    item.setSuperior(userBaseVo.getMerge());
                }
            }
        });
        return reportList;
    }

    @Override
    public int insertInfo(EntReport entReport) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), true), entReport);
        entReport.setNumber(String.valueOf(System.nanoTime()));
        return entReportMapper.insert(entReport);
    }

    @Override
    public int updateInfo(EntReport entReport) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), false), entReport);
        return entReportMapper.updateById(entReport);
    }

    @Override
    public EntReportVo details(Long id) {
        EntReportVo entReportVo = new EntReportVo();
        EntReport report = entReportMapper.selectById(id);
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        BeanUtils.copyProperties(report, entReportVo);

        List<Long> arrayList = new ArrayList<>();
        Long superior = null;
        Long reporter = null;
        Long compile = null;
        Long instructPerson = null;
        if (StringUtils.isNotBlank(report.getSuperior())) {
            superior = Long.parseLong(report.getSuperior());
            arrayList.add(superior);
        }
        if (StringUtils.isNotBlank(report.getReporter())) {
            reporter = Long.parseLong(report.getReporter());
            arrayList.add(reporter);
        }
        if (StringUtils.isNotBlank(report.getCompile())) {
            compile = Long.parseLong(report.getCompile());
            arrayList.add(compile);
        }
        if (StringUtils.isNotBlank(report.getInstructPerson())) {
            instructPerson = Long.parseLong(report.getInstructPerson());
            arrayList.add(instructPerson);
        }
        List<Long> joints = Arrays.asList(StringsUtils.convert(report.getJoint().split(",")));
        List<Long> makes = Arrays.asList(StringsUtils.convert(report.getMake().split(",")));
        arrayList.addAll(joints);
        arrayList.addAll(makes);

        arrayList.stream().distinct().collect(Collectors.toList());
        List<UserBaseVo> listUser = userService.listName(arrayList.toArray(new Long[arrayList.size()]));

        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        for (UserBaseVo userBaseVo : listUser) {
            if (superior == userBaseVo.getId()) {
                entReportVo.setSuperior(userBaseVo.getMerge());
            }
            if (reporter == userBaseVo.getId()) {
                entReportVo.setReporter(userBaseVo.getMerge());
            }
            if (compile == userBaseVo.getId()) {
                entReportVo.setCompile(userBaseVo.getMerge());
            }
            if (instructPerson == userBaseVo.getId()) {
                entReportVo.setInstructPerson(userBaseVo.getMerge());
            }
            if (joints.contains(userBaseVo.getId())) {
                list1.add(userBaseVo.getMerge());
            }
            if (makes.contains(userBaseVo.getId())) {
                list2.add(userBaseVo.getMerge());
            }
        }
        entReportVo.setJoints(list1);
        entReportVo.setMakes(list2);
        return entReportVo;
    }

    @Override
    public int addMake(Long reportId, Long[] makes) {
        EntReport report = entReportMapper.selectById(reportId);
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        if (StringUtils.isNotBlank(report.getMake())) {
            report.setMake(report.getMake() + "," + makes.toString());
        } else {
            report.setMake(makes.toString());
        }

        return updateInfo(report);
    }

    @Override
    public JSONArray jurisdiction(Long reportId) {
        JSONArray jsonArray = new JSONArray();
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        EntReport report = entReportMapper.selectById(reportId);
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        List<Long> joints = Arrays.asList(StringsUtils.convert(report.getJoint().split(",")));
        List<Long> makes = Arrays.asList(StringsUtils.convert(report.getMake().split(",")));
        if (report.getSuperior().equals(loginUser.getId().toString())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "superior");
            jsonObject.put("name", "上级");
            jsonArray.add(jsonObject);
        }
        if (report.getReporter().equals(loginUser.getId().toString())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "reporter");
            jsonObject.put("name", "汇报人");
            jsonArray.add(jsonObject);
        }
        if (report.getCompile().equals(loginUser.getId().toString())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "compile");
            jsonObject.put("name", "编制");
            jsonArray.add(jsonObject);
        }
        if (report.getInstructPerson().equals(loginUser.getId().toString())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "instructPerson");
            jsonObject.put("name", "批示人");
            jsonArray.add(jsonObject);
        }

        if (joints.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "joint");
            jsonObject.put("name", "联名汇报");
            jsonArray.add(jsonObject);
        }
        if (makes.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "make");
            jsonObject.put("name", "抄送");
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @Override
    public int addDeclare(Long id, String instructDeclare) {
        EntReport report = entReportMapper.selectById(id);
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        report.setInstructDeclare(instructDeclare);
        return updateInfo(report);
    }

    @Override
    public int addExecute(Long id, String instructExecute) {
        EntReport report = entReportMapper.selectById(id);
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        report.setInstructExecute(instructExecute);
        return updateInfo(report);
    }

    @Override
    public int addInstruct(EntReportInstructDto entReportInstructDto) {
        EntReport report = entReportMapper.selectById(entReportInstructDto.getId());
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        report.setInstructType(entReportInstructDto.getType());
        report.setInstructGist(entReportInstructDto.getGist());
        report.setInstructContent(entReportInstructDto.getContent());
        report.setInstructRecord(entReportInstructDto.getRecord());
        report.setInstructPicture(entReportInstructDto.getPicture());
        report.setInstructPerson(entReportInstructDto.getPerson());
        report.setInstructTime(new Date());
        return updateInfo(report);
    }

    @Override
    public int addAgain(EntReportInstructDto entReportInstructDto) {
        EntReport report = entReportMapper.selectById(entReportInstructDto.getId());
        if (report == null) {
            throw new RuntimeException("记录没有找到！");
        }
        report.setAgainType(entReportInstructDto.getType());
        report.setAgainGist(entReportInstructDto.getGist());
        report.setAgainContent(entReportInstructDto.getContent());
        report.setAgainRecord(entReportInstructDto.getRecord());
        report.setAgainPicture(entReportInstructDto.getPicture());
        report.setAgainPerson(entReportInstructDto.getPerson());
        report.setAgainTime(new Date());
        return updateInfo(report);
    }
}
